package com.ckd.flyingtrip.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.adapter.MeBatteryAdapter;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.fragment.HomeFragment;
import com.ckd.flyingtrip.javabean.UserInfoBean;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.Tools;
import com.ckd.flyingtrip.utils.VolleyErrorUtils;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MeBatteryActivity extends BaseActivity {


    @BindView(R.id.toolber_color_title)
    TextView title;
    @BindView(R.id.toolber_color_right)
    TextView right;
    @BindView(R.id.activity_me_battery_recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.activity_me_battery_no)
    TextView no;

    private MeBatteryAdapter adapter;
    private List<String> list = new ArrayList<>();

    private String bindingBattery = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_battery);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();

    }

    private void initListener() {
        adapter.setOnItemClickListener(new MeBatteryAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                bindingBattery = list.get(position);
                Intent intent = new Intent(MeBatteryActivity.this, CaptureActivity.class);
                ZxingConfig config = new ZxingConfig();
                config.setShowAlbum(false);
                intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                startActivityForResult(intent, Constants.ZXINGE_MAIN);
            }
        });
    }

    private void initData() {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.QINGQIUGERENXINXI, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("用户信息", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    switch (code) {
                        case "0":
                            toast(msg);
                            break;
                        case "1":
                            JSONObject dataInfo = json.getJSONObject("data");
                            String data = json.getString("data");
                            UserInfoBean userInfoBean = new Gson().fromJson(data, UserInfoBean.class);
                            BcUtils.setUserInfo(userInfoBean);
                            BcUtils.setUid(userInfoBean.getUserId());
                            BcUtils.setToken(userInfoBean.getToken());
                            BcUtils.setPhone(userInfoBean.getUserPhone());
                            BcUtils.setSignState(userInfoBean.getUserState());
                            BcUtils.setuserRent(userInfoBean.getUserRent());
                            BcUtils.setuserDeposit(userInfoBean.getUserDeposit());
                            BcUtils.setbindingElectricBicycle(userInfoBean.getBindingElectricBicycle());
                            HomeFragment.userStart = Integer.parseInt(userInfoBean.getUserState());

                            if (userInfoBean.getBindingBattery().equals("")) {
                                recyclerView.setVisibility(View.GONE);
                                no.setVisibility(View.VISIBLE);
                            } else {
                                no.setVisibility(View.GONE);
                                recyclerView.setVisibility(View.VISIBLE);
                                String[] strings = userInfoBean.getBindingBattery().split(",");
                                for (int i = 0; i < strings.length; i++) {
                                    list.add(strings[i]);
                                }
                                if (adapter != null)
                                    adapter.notifyDataSetChanged();
                            }
                            break;
                        case "2":
                            startActivity(new Intent(MeBatteryActivity.this, UserLogInActivity.class));
                            Tools.closeLogIN(MeBatteryActivity.this);
                            finish();
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismisProgressDialog();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
                VolleyErrorUtils.checkError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("userPhone", BcUtils.getUserInfo().getUserPhone());
                    json_url.put("token", BcUtils.getToken());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initView() {
        title.setText("我的电池");
        right.setText("换电记录");
        right.setVisibility(View.VISIBLE);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MeBatteryAdapter(this, list);
        recyclerView.setAdapter(adapter);
    }

    @OnClick({R.id.toolber_color_back, R.id.toolber_color_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolber_color_back:
                finish();
                break;
            case R.id.toolber_color_right:
                Intent intent = new Intent(this, MeBatteryRecordActivity.class);
                intent.putExtra("type", "1");
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.ZXINGE_MAIN && resultCode == this.RESULT_OK) {
            String content = data.getStringExtra(Constant.CODED_CONTENT);
            initZxingData(content);
//            机柜码 CDZD08KXHD190401298
//            电池码 {"code":"BT206002008KXZL190619019","chk":"66be2dd98a6e3e49c4cdd5a08a027bfd"}
        }
    }

    private void initZxingData(String code) {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.powerout, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i("扫码退电", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        toast(msg);
                    } else {
                        toast(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("content", code);
                    json_url.put("sweepMark", "1");
                    json_url.put("bindingBattery", bindingBattery);
                    json_url.put("userBindingNum", BcUtils.getUserInfo().getUserBindingNum());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }
}
